<?php
apf_require_class("APF_DB_PDOStatement");
class APF_DB_PDO extends PDO {
    public function __construct($dsn, $username="", $password="", $driver_options=array()) {
        /*if ($username == 'caixh') {
            APF::get_instance()->get_logger()->error("PDO error:" . $dsn . "," . $_SERVER['REQUEST_URI']);
        }*/
        parent::__construct($dsn, $username, $password, $driver_options);
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('APF_DB_PDOStatement', array($this)));
        $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    }

    public function exec($statement) {
        if (APF::get_instance()->is_debug_enabled()) {
            APF::get_instance()->debug(__CLASS__ .'['. $this->name .']'. "->exec: $statement");
        }
        $logger = APF::get_instance()->get_logger();
        $logger->debug(__CLASS__, '['. $this->name .']->exec: ', $statement);
        $stmt = parent::exec($statement);
        if ($stmt instanceof PDOStatement) {
            $stmt->setFetchMode($this->default_fetch_mode);
        } else {
            $error_info = parent::errorInfo();
            if (parent::errorCode() !== '00000') {
                trigger_error($statement.' | '.join(' | ',$error_info),E_USER_ERROR);
            }

        }
        return $stmt;
    }

    public function prepare($statement, $driver_options=array()) {
        $stmt = parent::prepare($statement, $driver_options);
        if ($stmt instanceof PDOStatement) {
            $stmt->setFetchMode($this->default_fetch_mode);
        }
        return $stmt;
    }

    public function query($statement, $pdo=NULL, $object=NULL) {
        if (APF::get_instance()->is_debug_enabled()) {
            APF::get_instance()->debug(__CLASS__ .'['. $this->config['dsn'] .'|'.$this->name.']'. "->query: $statement");
        }
        $logger = APF::get_instance()->get_logger();
        $logger->debug(__CLASS__, '['. $this->name .']->query: ', $statement);
        $stmt = parent::query($statement, $pdo, $object);
            if ($stmt instanceof PDOStatement) {
            $stmt->setFetchMode($this->default_fetch_mode);
        }
        return $stmt;
    }

    public function set_name($name) {
        $this->name = $name;
        $this->config = APF::get_instance()->get_config($name, "database");
    }

    public function get_name() {
        return $this->name;
    }

    private $name;

    public $config;

    public function set_default_fetch_mode($mode) {
        $this->default_fetch_mode = $mode;
    }

    private $default_fetch_mode = PDO::FETCH_BOTH;
}
